﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;

using Sogeti.QueryWrapper;
using Sogeti.VSExtention;

using System.Reflection;

namespace Mskold.IterationManager
{
    /// <summary>
    /// Interaction logic for NewIteration.xaml
    /// </summary>
    public partial class NewIteration : Window
    {
        public string str_NEW_ITERATION_MARK = "INSERT NEW ITERATION";
        private IterationManagerConfig config;
        private TeamExplorerIntergator teamExplorerIntegrator;

        public NewIteration()
        {
            InitializeComponent();
        }

        public NewIteration(TeamExplorerIntergator teIntegrator)
        {
            InitializeComponent();

            teamExplorerIntegrator = teIntegrator;

            vm = new NewIterationViewModel();

            vm.Load(teamExplorerIntegrator);
            this.DataContext = vm;


    
        }


        private void cmdCreateIteration_Click(object sender, RoutedEventArgs e)
        {
            vm.cmdCreateIteration(this);
            Close();
        }
       
        private void cmdCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

     
 
        #region "Drag and Drop"

        Point _lastMouseDown;
        XmlElement draggedItem, _target;

        private void treeView1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                _lastMouseDown = e.GetPosition(treeView2);
            }

        }
        private void treeView1_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    Point currentPosition = e.GetPosition(treeView2);


                    if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 10.0) ||
                        (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
                    {
                        draggedItem = (XmlElement)treeView2.SelectedItem;
                        if (draggedItem != null)
                        {
                            DragDropEffects finalDropEffect = DragDrop.DoDragDrop(treeView2, treeView2.SelectedValue,
                                DragDropEffects.Move);
                            //Checking target is not null and item is dragging(moving)
                            if ((finalDropEffect == DragDropEffects.Move) && (_target != null))
                            {
                                // A Move drop was accepted
                                if (!draggedItem.Attributes["Path"].Value.ToString().Equals(_target.Attributes["Path"].Value.ToString()))                          
                                {
                                    CopyItem(draggedItem, _target);
                                    _target = null;
                                    draggedItem = null;
                                }

                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
        private void treeView1_DragOver(object sender, DragEventArgs e)
        {
            try
            {

                Point currentPosition = e.GetPosition(treeView2);


                if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 10.0) ||
                    (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
                {
                    //// Verify that this is a valid drop and then store the drop target
                    //TreeViewItem item = GetNearestContainer(e.OriginalSource as UIElement);
                    //if (CheckDropTarget(draggedItem, item))
                    //{
                    //    e.Effects = DragDropEffects.Move;
                    //}
                    //else
                    //{
                    //    e.Effects = DragDropEffects.None;
                    //}
                }
                e.Handled = true;
            }
            catch (Exception)
            {
            }
        }
          private void treeView1_Drop(object sender, DragEventArgs e)
          {
              try
              {
                  //e.Effects = DragDropEffects.None;
                  //e.Handled = true;
  
                  //// Verify that this is a valid drop and then store the drop target
                  //XmlElement TargetItem = GetNearestContainer(e.OriginalSource as UIElement);
                  //if (TargetItem != null && draggedItem != null )
                  //{
                  //    _target = TargetItem;
                  //    e.Effects = DragDropEffects.Move;
  
                  //}
              }
              catch (Exception)
              {
         }
  
  
  
          }
          private bool CheckDropTarget(XmlElement _sourceItem, XmlElement _targetItem)
          {
              //Check whether the target item is meeting your condition
              bool _isEqual = false;
              if (!_sourceItem.Attributes["Path"].Value.ToString().Equals(_targetItem.Attributes["Path"].Value.ToString()))
              {
                  _isEqual = true;
              }
              return _isEqual;

          }
      
            private void CopyItem(XmlElement _sourceItem, XmlElement _targetItem)
          {
  
                try
                {
                    ////adding dragged TreeViewItem in target TreeViewItem
                    //addChild(_sourceItem, _targetItem);
  
                    ////finding Parent TreeViewItem of dragged TreeViewItem 
                    //TreeViewItem ParentItem = FindVisualParent<TreeViewItem>(_sourceItem);
                    //// if parent is null then remove from TreeView else remove from Parent TreeViewItem
                    //if (ParentItem == null)
                    //{
                    //    treeView1.Items.Remove(_sourceItem);
                    //}
                    //else
                    //{                        
                    //    ParentItem.Items.Remove(_sourceItem);
                    //}
                }
                catch
                {
  
                }
             }

     //     public void addChild(TreeViewItem _sourceItem,TreeViewItem _targetItem)
     //     {
     //         // add item in target TreeViewItem 
     //         TreeViewItem item1 = new TreeViewItem();
     //         item1.Header = _sourceItem.Header;
     //         _targetItem.Items.Add(item1);    
     //         foreach (TreeViewItem item in _sourceItem.Items)
     //         {
     //             addChild(item, item1);               
     //         }
     //     }
     //     static TObject FindVisualParent<TObject>(UIElement child) where TObject : UIElement
     //     {
     //         if (child == null)
     //         {
     //             return null;
     //         }
  
     //         UIElement parent = VisualTreeHelper.GetParent(child) as UIElement;
  
     //         while (parent != null)
     //         {
     //             TObject found = parent as TObject;
     //             if (found != null)
     //             {
     //                 return found;
     //             }
     //             else
     //             {
     //                 parent = VisualTreeHelper.GetParent(parent) as UIElement;
     //             }
     //         }

     //      return null;
     //  }
     //  private TreeViewItem GetNearestContainer(UIElement element)
     //  {
     //      // Walk up the element tree to the nearest tree view item.
     //      TreeViewItem container = element as TreeViewItem;
     //     while ((container == null) && (element != null))
     //      {
     //          element = VisualTreeHelper.GetParent(element) as UIElement;
     //          container = element as TreeViewItem;
     //      }
     //      return container;
     // }

    #endregion


            //public static void SetSelectedItem(ref TreeView control, XmlElement item)
            //{
            //    try
            //    {
            //        DependencyObject dObject = control
            //            .ItemContainerGenerator
            //            .ContainerFromItem(item);

            //        //uncomment the following line if UI updates are unnecessary
            //        ((TreeViewItem)dObject).IsSelected = true;                

            //        MethodInfo selectMethod =
            //            typeof(TreeViewItem).GetMethod("Select",
            //            BindingFlags.NonPublic | BindingFlags.Instance);

            //        selectMethod.Invoke(dObject, new object[] { true });
            //    }
            //    catch { }
            //}
    

       private void cmdUp_Click(object sender, RoutedEventArgs e)
       {

           
           vm.cmdIterationUp((XmlElement)treeView2.SelectedItem);
           UpdateToolbarsButtons((XmlElement)treeView2.SelectedItem);
           
         
           //var bindingExpression = treeView2.GetBindingExpression(TreeView.ItemsSourceProperty);
           //bindingExpression.UpdateTarget();
           
           //DependencyObject dObject = treeView2
           //          .ItemContainerGenerator
           //          .ContainerFromItem(treeView2.SelectedItem);

           ////uncomment the following line if UI updates are unnecessary
           ////((TreeViewItem)dObject).IsSelected = true;         
           

           
       }

       private void cmdDown_Click(object sender, RoutedEventArgs e)
       {
           vm.cmdIterationDown((XmlElement)treeView2.SelectedItem);

           UpdateToolbarsButtons((XmlElement)treeView2.SelectedItem);

       }

       private void cmdIndent_Click(object sender, RoutedEventArgs e)
       {

           vm.cmdIterationIndent((XmlElement)treeView2.SelectedItem);

           UpdateToolbarsButtons((XmlElement)treeView2.SelectedItem);
       }

       private void cmdOutDent_Click(object sender, RoutedEventArgs e)
       {
            
           vm.cmdIterationOutdent((XmlElement)treeView2.SelectedItem);
           UpdateToolbarsButtons((XmlElement)treeView2.SelectedItem);
           //var bindingExpression = treeView2.GetBindingExpression(TreeView.ItemsSourceProperty);
           //bindingExpression.UpdateTarget();

       }

     

       private void cmdSettings_Click(object sender, RoutedEventArgs e)
       {

           SettingsDlg settingsDlg = new SettingsDlg(config, teamExplorerIntegrator);
           settingsDlg.ShowDialog();
       }

       private NewIterationViewModel vm;

       private void ToolBar_Loaded(object sender, RoutedEventArgs e)
       {
           ToolBar toolBar = sender as ToolBar;
           var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;
           if (overflowGrid != null)
           {
               overflowGrid.Visibility = Visibility.Collapsed;
           }

           XmlElement x = ((XmlElement)treeView2.SelectedItem);
           UpdateToolbarsButtons(x);
       }

       private void treeView2_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
       {  
           XmlElement x = ((XmlElement)treeView2.SelectedItem);
           UpdateToolbarsButtons( x);

       }

       private void  UpdateToolbarsButtons(XmlElement x)
       {
           bool bToolBarVisable = false;

           if (x != null)
           {
                if(x.GetAttribute("Name")!=null)
               {
                   if (x.Attributes["Name"].Value.ToString() == str_NEW_ITERATION_MARK)
                   {
                       cmdUp.IsEnabled = true;
                       cmdDown.IsEnabled = true;
                       cmdIndent.IsEnabled = true;
                       cmdOutDent.IsEnabled = true;


                       bToolBarVisable = true;
                       if (x.PreviousSibling == null)
                       {
                           cmdUp.IsEnabled = false;
                           cmdIndent.IsEnabled = false;
                       }
                       if (x.NextSibling == null)
                       {
                           cmdDown.IsEnabled = false;
                       }
                       if (x.ParentNode.ParentNode.Attributes["Name"].Value == "Iteration")
                       {
                           cmdOutDent.IsEnabled = false;
                       }

                   }
               }
           }
           toolbarTreeView.IsEnabled = bToolBarVisable;
          
       }


    }
}
